<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDepartmentTree } from '/@/api/system/department';
  import { addUser, getUser, updateUser } from '/@/api/system/user';
  // import { getPostList } from '/@/api/system/post';
  const { t } = useI18n();
  export const accountFormSchema: FormSchema[] = [
    {
      field: 'userName',
      label: t('用户名'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'password',
      label: t('密码'),
      component: 'InputPassword',
      required: true,
      ifShow: false,
      colProps: { span: 24 },
    },
    // {
    //   label: '角色',
    //   field: 'roles',
    //   component: 'ApiSelect',
    //   componentProps: {
    //     api: getRoleAllList,
    //     labelField: 'name',
    //     valueField: 'id',
    //   },
    //   required: true,
    // },
    {
      field: 'code',
      label: t('编号'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'departmentIds',
      label: t('所属机构'),
      component: 'TreeSelect',
      componentProps: {
        fieldNames: {
          label: 'name',
          key: 'id',
          value: 'id',
        },
        multiple: true,
        getPopupContainer: () => document.body,
      },
      required: true,
      colProps: { span: 24 },
    },
    // {
    //   field: 'postId',
    //   label: '所属岗位',
    //   component: 'ApiSelect',
    //   componentProps: {
    //     api: getPostList,
    //     // use name as label
    //     labelField: 'name',
    //     // use id as value
    //     valueField: 'id',
    //     getPopupContainer: () => document.body,
    //   },
    //   required: true,
    //   colProps: { span: 24 },
    // },
    {
      field: 'name',
      label: t('姓名'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      label: t('手机号码'),
      field: 'mobile',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      label: t('邮箱'),
      field: 'email',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'gender',
      label: t('性别'),
      component: 'Select',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        options: [
          { label: '男', value: 1 },
          { label: '女', value: 0 },
        ],
      },
    },
    {
      field: 'birthDate',
      label: '生日',
      component: 'DatePicker',
      colProps: { span: 24 },
      componentProps: {
        format: 'YYYY-MM-DD',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'address',
      label: '联系地址',
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'qqNumber',
      label: 'QQ',
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'wechatNumber',
      label: '微信',
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      label: t('备注'),
      field: 'remark',
      component: 'InputTextArea',
      colProps: { span: 24 },
    },
  ];

  export default defineComponent({
    name: 'UserModel',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { notification } = useMessage();
      const isUpdate = ref(true);
      const rowId = ref('');
      // const { t } = useI18n();

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.id;
          const record = await getUser(data.id);
          const departmentIds = record.departmentIds.split(',');
          setFieldsValue({
            ...record,
            departmentIds,
          });
        }
        const treeData = await getDepartmentTree();

        updateSchema([
          {
            field: 'password',
            ifShow: !unref(isUpdate),
          },
          {
            field: 'departmentIds',
            componentProps: { treeData },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? t('新增用户') : t('编辑用户')));

      async function handleSubmit() {
        try {
          const values = await validate();
          const data = { ...values, departmentIds: values.departmentIds.toString() };
          if (!unref(isUpdate)) {
            // 验证 密码必须包含大写字母、小写字母、数字和特殊字符，长度8~16位
            if (data.password.length < 8 || data.password.length > 16) {
              notification.error({
                message: t('密码'),
                description: t('密码须长度8~16位'),
              });
            }
            let pwdCount = 0;
            let pwdRegex1 = new RegExp('(?=.*[0-9]).{8,16}'); //纯数字
            let pwdRegex2 = new RegExp('(?=.*[a-z]).{8,16}'); //小写字母
            let pwdRegex3 = new RegExp('(?=.*[A-Z]).{8,16}'); //大写字母
            let pwdRegex4 = new RegExp('(?=.*[^a-zA-Z0-9]).{8,16}'); //特殊字符
            if (pwdRegex1.test(data.password)) {
              pwdCount = pwdCount + 1;
            }
            if (pwdRegex2.test(data.password)) {
              pwdCount = pwdCount + 1;
            }
            if (pwdRegex3.test(data.password)) {
              pwdCount = pwdCount + 1;
            }
            if (pwdRegex4.test(data.password)) {
              pwdCount = pwdCount + 1;
            }
            if (pwdCount < 4) {
              notification.error({
                message: t('密码'),
                description: t('须含大写,小写,数字和特殊字符'),
              });
              return;
            }
          }
          setModalProps({ confirmLoading: true });

          // TODO custom api
          if (!unref(isUpdate)) {
            //false 新增
            await addUser(data);
            notification.success({
              message: t('新增用户'),
              description: t('成功'),
            }); //提示消息
          } else {
            data.id = rowId.value;
            await updateUser(data);
            notification.success({
              message: t('编辑用户'),
              description: t('成功'),
            }); //提示消息
          }

          closeModal();
          emit('success');
        } catch (error) {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, t };
    },
  });
</script>
